package model

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/server/manager"
	"github.com/gomodule/redigo/redis"
)

var OneUserModel = &UserModel{}

type UserModel struct{}

const (
	RedisKeyName = "gochat.users"
	RedisAddr    = "0.0.0.0:6379"
	RedisNetwork = "tcp"
)

var RedisPool = &redis.Pool{
	Dial: func() (conn redis.Conn, e error) {
		return redis.Dial(RedisNetwork, RedisAddr)
	},
	MaxIdle:     3,
	MaxActive:   5,
	IdleTimeout: 240 * time.Second,
}

// 判断用户是否已登录
func (u *UserModel) CheckUserLogin(username int) (ok bool) {
	_, ok = manager.UserMgr.OnlineUsers[username]
	return
}

// 判断用户是否注册
func (u *UserModel) CheckUserExist(username int) (ok bool, err error) {
	conn := RedisPool.Get()
	defer conn.Close()
	ok, err = redis.Bool(conn.Do("HEXISTS", RedisKeyName, username))
	return
}

func (u *UserModel) GetUserByName(username int) (userProfile protocol.UserProfile, err error) {
	conn := RedisPool.Get()
	defer conn.Close()
	reply, err := redis.String(conn.Do("HGET", RedisKeyName, username))
	if err != nil {
		fmt.Printf("用户%d可能不存在\n", username)
		return
	}
	userProfile = protocol.UserProfile{}
	err = json.Unmarshal([]byte(reply), &userProfile)
	if err != nil {
		fmt.Printf("从数据库反序列化用户信息发生错误，%v\n", err)
		return
	}
	return
}

func (u *UserModel) SetUserInfo(username int, userProfile protocol.UserProfile) (err error) {
	jsonBytes, err := json.Marshal(userProfile)
	if err != nil {
		fmt.Printf("序列化用户信息发生错误，用户信息为：%v，错误信息为：%v\n", userProfile, err)
		return
	}
	conn := RedisPool.Get()
	defer conn.Close()
	_, err = conn.Do("HSET", RedisKeyName, username, string(jsonBytes))
	if err != nil {
		fmt.Printf("用户信息存到数据库发生错误，用户信息为：%v，错误信息为：%v\n", userProfile, err)
		return
	}
	return
}
